/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Optional;
import java.util.ServiceLoader;

/**
 * 多语列的SPI，获取当前语言
 */
public interface CAFCurrentLanguageResolver {

    /**
     * 获取当前的类型
     *
     * @return 类型
     */
    Type getType();

    /**
     * 获取当前语言
     */
    Optional<String> getLanguage();

    static CAFCurrentLanguageResolver getSessionInstance() {
        return CAFMultiLanguageResolverSelector.sessionInstance;
    }

    static CAFCurrentLanguageResolver getRequestInstance() {
        return CAFMultiLanguageResolverSelector.requestInstance;
    }

    class CAFMultiLanguageResolverSelector {
        //会话级别：Session > Request
        private static CAFCurrentLanguageResolver sessionInstance = null;
        //请求级别
        private static CAFCurrentLanguageResolver requestInstance = null;

        static {
            Logger log = LoggerFactory.getLogger(CAFCurrentLanguageResolver.class);
            ServiceLoader<CAFCurrentLanguageResolver> resolvers = ServiceLoader.load(CAFCurrentLanguageResolver.class);
            for (CAFCurrentLanguageResolver resolver : resolvers) {
                if (resolver.getType() == Type.Session) {
                    sessionInstance = resolver;
                } else if (resolver.getType() == Type.Request) {
                    requestInstance = resolver;
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("current CAFCurrentLanguageResolver of session [{}]", sessionInstance.getClass().getName());
                log.debug("current CAFCurrentLanguageResolver of request [{}]", requestInstance != null ? requestInstance.getClass().getName() : null);
            }
            Assert.notNull(sessionInstance, "[CAFCurrentLanguageResolver] is null, please check.");
        }
    }

    enum Type {
        Session,
        Request
    }

}
